package com.ybt.heartratem.moudle.main;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProviders;

import com.ybt.heartratem.R;
import com.ybt.heartratem.common.app.AppController;
import com.ybt.heartratem.common.app.AppViewModelFactory;
import com.ybt.heartratem.common.app.CacheManager;
import com.ybt.heartratem.common.app.Injection;
import com.ybt.heartratem.common.app.MyApplication;
import com.ybt.heartratem.databinding.ActivitySplBinding;
import com.ybt.heartratem.moudle.MainActivity;
import com.ybt.heartratem.moudle.MainVM;

import me.goldze.mvvmhabit.BR;
import me.goldze.mvvmhabit.base.BaseActivity;

public class SplActivity extends BaseActivity<ActivitySplBinding, MainVM> {
    private static final int REQUEST_PERMISSION = 1;

    @Override
    public MainVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(MyApplication.getInstance());
        return ViewModelProviders.of(this, factory).get(MainVM.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_spl;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        initPermissionsManager();
        new CacheManager().init();
        AppController.mMainHandler.postDelayed(() -> {
            if (TextUtils.isEmpty(Injection.aasDataRe().getUserName())) {
                startActivity(BindDeviceActivity.class);
            } else {
                startActivity(MainActivity.class);
            }
            finish();
        }, 500);
    }

    private void initPermissionsManager() {
        ActivityCompat.requestPermissions(this,
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.RECEIVE_BOOT_COMPLETED,
                        Manifest.permission.INTERNET,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_SETTINGS,
                        Manifest.permission.WRITE_SECURE_SETTINGS}, REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION:
                new CacheManager().init();
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}